<template>
  <component
    is="a-modal"
    v-model:visible="visible"
    :width="1200"
    :title="title"
    :mask-closable="false"
    :ok-loading="loading"
    @cancel="close"
    @before-ok="submit">
    <!-- 表单信息 start -->
    <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
		<a-form-item label="排序" field="sort_order">
		  <a-input v-model="formData.sort_order" placeholder="请输入排序" />
		</a-form-item>
      <a-form-item label="活动分类" field="activity_category_id">
        <a-select v-model="formData.activity_category_id" :options="postData" placeholder="请选择活动分类" allow-clear />
      </a-form-item>
      <a-form-item label="活动封面" field="activity_cover">
        <sa-upload-image v-model="formData.activity_cover" :limit="3" :multiple="false" />
      </a-form-item>
      <a-form-item label="活动时间" field="activity_time_range">
      <a-range-picker v-model="formData.activity_time_range" :show-time="true"  mode="date"  />
	  </a-form-item>
	  
      <a-form-item label="省" field="province_id">
        <a-select
          v-model="formData.province_id"
          :options="provinceOptions"
          allow-clear
          placeholder="请选择所属省"
          @change="handleProvinceChange"
        />
      </a-form-item>
      <a-form-item label="市" field="city_id">
        <a-select
          v-model="formData.city_id"
          :options="cityOptions"
          allow-clear
          placeholder="请选择政市"
          :disabled="!formData.province_id"
          @change="handleCityChange"
        />
      </a-form-item>
      <a-form-item label="区" field="district_id">
        <a-select
          v-model="formData.district_id"
          :options="districtOptions"
          allow-clear
          placeholder="请选择区"
          :disabled="!formData.city_id"
        />
      </a-form-item>
      <a-form-item label="活动地址" field="activity_address">
        <a-input v-model="formData.activity_address" placeholder="请输入活动地址" />
      </a-form-item>
	  <a-form-item label="是否展示" field="is_display">
		<sa-switch v-model="formData.is_display" checkedText="是"  uncheckedText="否"/>
	  </a-form-item>
      <a-form-item label="活动标题" field="activity_title">
        <a-input v-model="formData.activity_title" placeholder="请输入活动标题" />
      </a-form-item>
      <a-form-item label="活动详情" field="activity_details">
        <ma-wangEditor v-model="formData.activity_details" :height="400" />
      </a-form-item>
    </a-form>
    <!-- 表单信息 end -->
  </component>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import api from '../api/activity'
import commonApi from '@/api/common'

const emit = defineEmits(['success'])
// 引用定义
const visible = ref(false)
const loading = ref(false)
const formRef = ref()
const mode = ref('')
const provinceOptions = ref([])
const cityOptions = ref([])
const districtOptions = ref([])
const postData = ref([])

let title = computed(() => {
  return '活动列表' + (mode.value == 'add' ? '-新增' : '-编辑')
})

// 表单信息
const formData = reactive({
  activity_id: null,
  lang_code: '',
  activity_category_id: null,
  sort_order: 0,
  activity_cover: '',
  activity_start_time: '',
  province_id: 0,
  city_id: 0,
  district_id: 0,
  activity_end_time: '',
  activity_address: '',
  is_display: 0,
  activity_title: '',
  activity_details: '',
   activity_time_range:[]
})

// 验证规则
const rules = {
  lang_code: [{ required: true, message: '语言代码必需填写' }],
  activity_category_id: [{ required: true, message: '活动分类必需填写' }],
  activity_cover: [{ required: true, message: '活动封面必需填写' }],
  activity_start_time: [{ required: true, message: '活动开始时间必需填写' }],
  province_id: [{ required: true, message: '省必需填写' }],
  activity_end_time: [{ required: true, message: '活动结束时间必需填写' }],
  city_id: [{ required: true, message: '市必需填写' }],
  district_id: [{ required: true, message: '区必需填写' }],
  activity_address: [{ required: true, message: '活动地址必需填写' }],
  is_display: [{ required: true, message: '展示/下架必需填写' }],
  activity_title: [{ required: true, message: '活动标题必需填写' }],
  activity_details: [{ required: true, message: '活动详情必需填写' }],
}

// 打开弹框
const open = async (type = 'add') => {
  mode.value = type
  visible.value = true
  formRef.value.resetFields()
  await initPage()
}

// 初始化页面数据
const initPage = async () => {
	const postResp = await commonApi.commonGet('/cassification/ClassificationDictionary/getCate',{classification_type:17})
	
	postData.value = postResp.data
}
// 加载省份数据
const loadProvinces = async () => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect',{level:1}) // 替换为实际获取省份的 API 地址
  provinceOptions.value = resp.data.map(item => ({
    value: item.value,
    label: item.label
  }))

}

// 加载城市数据
const loadCities = async (provinceId) => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect', {level:2,parent_code:provinceId }) // 替换为实际获取城市的 API 地址
  cityOptions.value = resp.data.map(item => ({
   value: item.value,
   label: item.label
  }))
  // 清空市选择后，同时清空区选择
  formData.city_id = 0
  formData.district_id = 0 
}

// 加载区县数据
const loadDistricts = async (cityId) => {
  const resp = await commonApi.commonGet('/Cnarea/Cnarea/getSelect', { level:3,parent_code:cityId }) // 替换为实际获取区县的 API 地址
  districtOptions.value = resp.data.map(item => ({
   value: item.value,
   label: item.label
  }))
  formData.district_id = 0
}

// 省选择变化处理
const handleProvinceChange = async (provinceId) => {
  if (provinceId) {
    await loadCities(provinceId)
  } else {
   
    formData.city_id = 0
    formData.district_id = 0
  }
}

// 市选择变化处理
const handleCityChange = async (cityId) => {
  if (cityId) {
    await loadDistricts(cityId)
  } else {
    formData.district_id = 0
  }

}

// 设置数据
const setFormData = async (data) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      formData[key] = data[key]
    }
  }
  await loadProvinces()
  // 若有省市区数据，重新加载对应数据
  if (data.province_id!=='') {
    await loadCities(data.province_id)
    if (data.city_id!=='') {
      await loadDistricts(data.city_id)
    }
  }
  formData.activity_time_range=[formData.activity_start_time,formData.activity_end_time]
  console.log(formData)
}

// 数据保存
const submit = async (done) => {
  const validate = await formRef.value?.validate()
  // if (!validate) {
    loading.value = true
    let data = { ...formData }
    let result = {}
    if(data.city_id=='') data.city_id=0
    if(data.district_id=='') data.city_id=0
      const [activity_start_time, activity_end_time] = formData.activity_time_range;
    const submitData = formData;
    submitData.activity_start_time=activity_start_time
    submitData.activity_end_time=activity_end_time
    if (mode.value === 'add') {
      // 添加数据
      data.activity_id = undefined
      result = await api.save(data)
    } else {
      // 修改数据
      result = await api.update(data.activity_id, data)
    }
    if (result.code === 200) {
      Message.success('操作成功')
      emit('success')
      done(true)
    }
    // 防止连续点击提交
    setTimeout(() => {
      loading.value = false
    }, 500)
  // }
  done(false)
}

// 关闭弹窗
const close = () => (visible.value = false)

defineExpose({ open, setFormData })
</script>
